import { ref, reactive, watch } from 'vue'

// 本地存储的key
const STORAGE_KEY = 'drift-bottle-data'

// 默认数据
const defaultData = [
]

// 从本地存储加载数据
const loadFromStorage = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      const parsed = JSON.parse(stored)
      // 将日期字符串转换回Date对象
      return parsed.map(bottle => ({
        ...bottle,
        createdAt: new Date(bottle.createdAt),
        replies: bottle.replies.map(reply => ({
          ...reply,
          createdAt: new Date(reply.createdAt)
        }))
      }))
    }
  } catch (error) {
    console.error('加载本地数据失败:', error)
  }
  return defaultData
}

// 保存到本地存储
const saveToStorage = (data) => {
  try {
    localStorage.setItem(STORAGE_KEY, JSON.stringify(data))
  } catch (error) {
    console.error('保存到本地存储失败:', error)
  }
}

// 全局瓶子数据存储
const sentBottles = ref(loadFromStorage())

// 监听数据变化，自动保存到本地存储
watch(sentBottles, (newData) => {
  saveToStorage(newData)
}, { deep: true })

// 瓶子状态管理
export const useBottleStore = () => {
  // 添加新瓶子
  const addBottle = (bottleData) => {
    const newBottle = {
      id: Date.now(),
      title: bottleData.title || '无标题',
      content: bottleData.content,
      tags: bottleData.tags ? bottleData.tags.split(',').map(tag => tag.trim()) : [],
      location: bottleData.location || '',
      mood: bottleData.mood || 'happy',
      status: 'active',
      createdAt: new Date(),
      views: 0,
      likes: 0,
      replies: []
    }
    sentBottles.value.unshift(newBottle)
    return newBottle
  }

  // 删除瓶子
  const deleteBottle = (bottleId) => {
    const index = sentBottles.value.findIndex(bottle => bottle.id === bottleId)
    if (index > -1) {
      sentBottles.value.splice(index, 1)
      return true
    }
    return false
  }

  // 更新瓶子
  const updateBottle = (bottleId, updateData) => {
    const bottle = sentBottles.value.find(b => b.id === bottleId)
    if (bottle) {
      Object.assign(bottle, updateData)
      return bottle
    }
    return null
  }

  // 获取瓶子
  const getBottle = (bottleId) => {
    return sentBottles.value.find(b => b.id === bottleId)
  }

  // 获取所有瓶子
  const getAllBottles = () => {
    return sentBottles.value
  }

  // 添加回复
  const addReply = (bottleId, replyData) => {
    const bottle = getBottle(bottleId)
    if (bottle) {
      const newReply = {
        id: Date.now(),
        username: replyData.username || '匿名用户',
        avatar: replyData.avatar || '/src/assets/images/avatar_default.png',
        content: replyData.content,
        createdAt: new Date()
      }
      bottle.replies.push(newReply)
      return newReply
    }
    return null
  }

  // 增加浏览量
  const incrementViews = (bottleId) => {
    const bottle = getBottle(bottleId)
    if (bottle) {
      bottle.views = (bottle.views || 0) + 1
    }
  }

  // 切换点赞状态
  const toggleLike = (bottleId) => {
    const bottle = getBottle(bottleId)
    if (bottle) {
      bottle.isLiked = !bottle.isLiked
      bottle.likes += bottle.isLiked ? 1 : -1
      return bottle.isLiked
    }
    return false
  }

  return {
    sentBottles,
    addBottle,
    deleteBottle,
    updateBottle,
    getBottle,
    getAllBottles,
    addReply,
    incrementViews,
    toggleLike
  }
}
